package api

import (
	"gitee.com/keepalived_0807/Vblog/apps/token"
	"gitee.com/keepalived_0807/Vblog/conf"
	"gitee.com/keepalived_0807/Vblog/ioc"
	"gitee.com/keepalived_0807/Vblog/response"
	"github.com/gin-gonic/gin"
)

func init() {
	ioc.Api.Registry(token.AppName, &TokenApiHandler{})
}

type TokenApiHandler struct {
	token token.Service
}

func (h *TokenApiHandler) Registry(appRouter gin.IRouter) {
	appRouter.POST("/", h.Login)
	appRouter.DELETE("/", h.Logout)
}

func (h *TokenApiHandler) Init() error {
	h.token = ioc.Controller.Get(token.AppName).(token.Service)
	subRouter := conf.C().Application.GinRootRouter().Group("token")
	h.Registry(subRouter)
	return nil
}

func (h *TokenApiHandler) Login(c *gin.Context) {
	req := token.NewIssueTokenRequest("", "")
	if err := c.BindJSON(req); err != nil {
		response.Failed(err, c)
		return
	}
	tk, err := h.token.IssueToken(c.Request.Context(), req)
	if err != nil {
		response.Failed(err, c)
		return
	}

	c.SetCookie(token.COOKIE_TOKEN_KEY, tk.AccessToken, tk.RefreshTokenExpiredAt, "/", conf.C().Application.Domain, false, true)
	response.Success(tk, c)
}

func (h *TokenApiHandler) Logout(c *gin.Context) {
	ak, err := c.Cookie(token.COOKIE_TOKEN_KEY)
	if err != nil {
		response.Failed(err, c)
		return
	}
	rt := c.GetHeader(token.REFRESH_HEADER_KEY)
	req := token.NewRevolkTokenRequest(ak, rt)
	tk, err := h.token.RevolkToken(c.Request.Context(), req)
	if err != nil {
		response.Failed(err, c)
		return

	}
	response.Success(tk, c)
}
